import {Component, Input, OnInit, Optional} from '@angular/core';
import {FormBuilder, FormGroup} from '@angular/forms';
import {NzDrawerRef, NzFormatEmitEvent, NzMessageService} from 'ng-zorro-antd';
import {Observable} from 'rxjs';
import {I18NService} from '@core/i18n/i18n.service';
import {PopupRes} from '@shared/popup/popup.interface';
import {BaseComponent} from '@shared/base/base.component';
import {QuestionService} from '../service/question.service';
import {RoleService} from '../../roles/service/role.service';
import {Question} from "../model/question";
import {comparisonValue} from "@shared/utils/data.utils";
import {KnowledgeService} from "../../knowledge/services/knowledge.service";
import {PopupService} from "@shared/popup/popup.service";
import {KnowledgeModifyComponent} from "./knowledge-modify.component";
import {Router} from "@angular/router";

@Component({
  selector: 'question-modify',
  templateUrl: './question-modify.html'
})

export class QuestionModifyComponent extends BaseComponent implements OnInit, PopupRes {

  _id: number;

  @Input()
  set id(val: number) {
    this._id = val;
  }

  validateForm: FormGroup;
  tempItem: Question;
  isCheck = true;
  page = {
    pageNo: 1,
    pageSize: 10
  };

  constructor(
    private fb: FormBuilder,
    private message: NzMessageService,
    private i18nService: I18NService,
    private userService: QuestionService,
    private roleService: RoleService,
    private knowledgeService: KnowledgeService,
    private questionService:QuestionService,
    private router:Router,
    private popupService: PopupService
  ) {
    super();
    this.validateForm = this.fb.group({
      content: null,
      answer: null,
      choiceA: null,
      choiceB: null,
      choiceC: null,
      choiceD: null,
      choiceE: null,
      choiceF: null,
      choiceG: null,
      choiceH: null,
      choiceNum:4,
      description: null,
      score: [0],
      difficulty: null,
      questionType:null,
      knowledgeId:0
    });
  }
  searchOptions = [];
  value: number;
  questionType='单选题';
  E=false;
  F=false;
  G=false;
  H=false;
  choiceNum=4;

  ngOnInit(): void {
    debugger
    if (this._id !== undefined) {
      this.getQuestionById(this._id);
    }
    this.getKnowledgeByPid(0);
  }

  addChoice():void{
    this.choiceNum=this.choiceNum+1;
    this.showChoice();

  }
  deleteChoice():void{
    this.choiceNum=this.choiceNum-1;
    this.showChoice();
  }
  showChoice():void{
    if (this.choiceNum==4){
      this.H=false;
      this.G=false;
      this.F=false;
      this.E=false;
    }
    if (this.choiceNum==5){
      this.E=true;
      this.F=false;
      this.G=false;
      this.H=false;
    }
    if (this.choiceNum==6){
      this.E=true;
      this.F=true;
      this.G=false;
      this.H=false;
    }
    if (this.choiceNum==7){
      this.E=true;
      this.F=true;
      this.G=true;
      this.H=false;
    }
    if (this.choiceNum==8){
      this.E=true;
      this.F=true;
      this.G=true;
      this.H=true;
    }
  }
  getQuestionById(id: number): void {
    this.questionService.getQuestionById(id)
      .subscribe(res => {
        this.tempItem = res;
        // if(res.picture!==null){
        //   res.content=res.content.concat(res.picture);
        // }
        this.validateForm.patchValue(res);
        if(this.validateForm.value.questionType=='单选题'||this.validateForm.value.questionType=='多选题'){
          this.choiceNum=this.validateForm.value.choiceNum;
          this.showChoice();
        }

      });
  }
  changeAnswer(value: string[]): void {
    this.validateForm.value.answer=value.join(',');
  }
  cancel(): Observable<any> {
    return undefined;
  }
  addSubmit():void {
      if (this.isCheck) {
        this.isCheck = false;
        if(this.validateForm.value.questionType=='单选题'||this.validateForm.value.questionType=='多选题'){
          this.validateForm.value.choiceNum=this.choiceNum;
        }
        this.add(this.validateForm.value).subscribe(res => {
          // this.router.navigate(['/main/question/questionList']]);
        }, err => {
        });
      }


  }
  submit(): Observable<any> {
    return new Observable((sub) => {
      if (this.isCheck) {
        this.isCheck = false;
        if(this.validateForm.value.questionType=='单选题'||this.validateForm.value.questionType=='多选题'){
          this.validateForm.value.choiceNum=this.choiceNum;
        }
        if (this._id !== undefined) {
          const saveVal: Question = {
            id: this._id,
            ...comparisonValue(this.validateForm.value, this.tempItem)
          };
          this.update(saveVal).subscribe(res => {
            sub.next();
          }, err => {
            sub.error();
          });
        } else {
          this.add(this.validateForm.value).subscribe(res => {
            sub.next();
          }, err => {
            sub.error();
          });
        }
      }
    });
  }

  add(item: Question): Observable<void> {
    return new Observable((sub) => {
      this.questionService.addQuestion(item)
        .subscribe(res => {
          this.message.success(this.i18nService.translate('modify.return.add_success'));
          this.isCheck = true;
          sub.next();
        }, err => {
          this.isCheck = true;
          sub.error();
        });
    });
  }

  update(item: Question): Observable<void> {
    return new Observable((sub) => {
      this.questionService.updateQuestion(item)
        .subscribe(res => {
          if (res) {
            this.message.success(this.i18nService.translate('modify.return.edit_success'));
          } else {
            this.message.error(this.i18nService.translate('modify.return.eidt_error'));
          }
          this.isCheck = true;
          sub.next();
        }, err => {
          this.isCheck = true;
          sub.error();
        });
    });
  }

  getKnowledgeByPid(pid: number): void {
    this.knowledgeService.getKnowledgeByPid(pid)
      .subscribe(res => {
        this.searchOptions = res;
      });
  }

  onExpandChange(e: NzFormatEmitEvent): void {
    if (e.node.getChildren().length === 0 && e.node.isExpanded) {
      this.knowledgeService.getKnowledgeByPid(parseInt(e.node.origin.key, 0))
        .subscribe(res => {
          e.node.addChildren(res);
        });
      this.value = e.node.origin.key;
    }
  }

  addKnowledge(item?: any): void {
    let params = {};
    let title = '添加菜单';
    this.popupService.create({
      title: title,
      content: KnowledgeModifyComponent,
      componentParams: params,
      width: 620,
      onSubmit: (res) => {
        // this.getKnowledgeByPid(0);
      },
      onCancel: (res) => {
        console.log(res);
      }
    }).afterClose.subscribe(res => {
      console.log(res);
    });
  }

}
